package com.example.cloudgateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AddRespHeaderGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    /**
     * 为响应头 添加自定义响应头信息
     *
     * @param config
     * @return
     */
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                log.info("打印添加响应头信息:{}:{}", config.getName(), config.getValue());
                // 获取request就可以进行修改了
                // 设置请求值
//                ServerHttpRequest modifiedRequest = exchange.getRequest().mutate().build();
//                ServerHttpRequest modifiedRequest = exchange.getRequest().mutate()
//                        .header(config.getName(), config.getValue()).build();
//                ServerWebExchange modifiedExchange = exchange.mutate().request(modifiedRequest).build();
//                return chain.filter(modifiedExchange);
                String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
                //在响应的请求头上 添加自定义的信息
                exchange.getResponse().getHeaders().add(config.getName(), value);
                return chain.filter(exchange);
            }
        };
    }
}
